﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Threading;
using DataLayer;

namespace ZombieMonkeys.Vibria.GUI
{
    public partial class GridView : PhoneApplicationPage
    {
        private bool solver = false;
        
        private string difficulty;

        ButtonGrid buttonGrid1;

        Logic.PuzzleSolver puzzleSolver;

        //initialize the timer
        System.Windows.Threading.DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer();
        int count = 0;

        /// <summary>
        /// Instantiates the Gridview page
        /// </summary>
        public GridView()
        {
            //Supported rotations
            SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape;

            InitializeComponent();

            buttonGrid1 = new ButtonGrid();
            ContentPanel.Children.Add(buttonGrid1);
            Grid.SetColumn(buttonGrid1, 1);
            Grid.SetRow(buttonGrid1, 2);

            //send a reference of this class to the buttongrid control
            buttonGrid1.SetGridView = this;

            //  DispatcherTimer setup
            timer.Tick += new EventHandler(timer_Tick);
            timer.Interval = new TimeSpan(0, 0, 1);
            timer.Start();
        }

        /// <summary>
        /// Called each time one of the number buttons in the button control is clicked
        /// </summary>
        public void CheckPuzzle()
        {
            if (puzzleSolver.PuzzleSolved())
            {
                //stop the timer
                timer.Stop();
                if (!solver)
	            {
                    //bring up the message box
                    MessageBoxResult result = MessageBox.Show("You solved the puzzle in " + String.Format("{0:D2}:{1:D2}", TimeSpan.FromSeconds(count).Minutes, TimeSpan.FromSeconds(count).Seconds), "Congratulations!!", MessageBoxButton.OK);
                    if (result == MessageBoxResult.OK)
                    {
                        //Here is where we should record data from the game
                        NavigationService.GoBack();
                    }
		        }
            }
        }

        /// <summary>
        /// Tells the puzzle solver to give the user just one little hint
        /// </summary>
        public void GiveMeAHint()
        {
            puzzleSolver.HintMode = true;
            puzzleSolver.solvePuzzle();
            puzzleGrid1.Update();
        }

        /// <summary>
        /// Screw hints, just solve my puzzle!!
        /// </summary>
        public void SolveMyPuzzle()
        {
            puzzleSolver.HintMode = false;
            puzzleSolver.solvePuzzle();
        }

        /// <summary>
        /// Timer_tick is called every tick and will update the text of the timeblock
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer_Tick(object sender, EventArgs e)
        {
            // Updating the Label which displays the timer
            count++;
            this.PageTitle.Text = difficulty + " Puzzle " + String.Format("{0:D2}:{1:D2}", TimeSpan.FromSeconds(count).Minutes, TimeSpan.FromSeconds(count).Seconds);
            buttonGrid1.timeBlock.Text = String.Format("{0:D2}:{1:D2}", TimeSpan.FromSeconds(count).Minutes, TimeSpan.FromSeconds(count).Seconds);
        }

        /// <summary>
        /// Called any time the page is navigated to
        /// </summary>
        /// <param name="e"></param>
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            difficulty = this.NavigationContext.QueryString["parameter"];
            puzzleGrid1.Difficulty = difficulty;
            if (difficulty == "Solve")
            {
                //sets the page to solver mode where the solve button is visible and the hint button is not
                solver = true;
                this.PageTitle.Text = difficulty + " Puzzle";
                buttonGrid1.solveButton.Visibility = Visibility.Visible;
                buttonGrid1.hintButton.Visibility = Visibility.Collapsed;
            }
            else
            {
                buttonGrid1.solveButton.Visibility = Visibility.Visible;
                buttonGrid1.solveButton.Content = "Save";
            }
            if (difficulty == "Load")
            {
                PuzzleLoader loader = new PuzzleLoader();
                puzzleGrid1.PopulateGrid(loader.Load(this.NavigationContext.QueryString["Id"]));
            }
            this.PageTitle.Text = difficulty + " Puzzle ";

            puzzleSolver = new Logic.PuzzleSolver(puzzleGrid1.puzzleGridList);

            base.OnNavigatedTo(e);
        }

        /// <summary>
        /// Method to save any game data when the user uses the back button to navigate away
        /// </summary>
        /// <param name="e"></param>
        protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            //This is where we need to record game data when the user navigates away from the page
            base.OnNavigatingFrom(e);
        }

        /// <summary>
        /// Called when the phone page orientation is changed
        /// </summary>
        /// <param name="e"></param>
        protected override void OnOrientationChanged(OrientationChangedEventArgs e)
        {
            switch (e.Orientation)
            {
                    //when the phone turns so should the screen
                case PageOrientation.Landscape:
                case PageOrientation.LandscapeLeft:
                case PageOrientation.LandscapeRight:
                    TitlePanel.Visibility = Visibility.Collapsed;
                    Grid.SetColumn(buttonGrid1, 2);
                    Grid.SetRow(buttonGrid1, 1);
                    buttonGrid1.RotateVertical();
                    if (!solver)
                    {
                        //turn on the timer text block if not the solver page
                        buttonGrid1.timeBlock.Visibility = Visibility.Visible;
                    }
                    break;
                case PageOrientation.Portrait:
                case PageOrientation.PortraitUp:
                case PageOrientation.PortraitDown:
                    //The title panel is invisible when in landscape
                    TitlePanel.Visibility = Visibility.Visible;
                    Grid.SetColumn(buttonGrid1, 1);
                    Grid.SetRow(buttonGrid1, 2);
                    buttonGrid1.RotateHorizontal();
                    if (!solver)
                    {
                        //switch the timer if not the solver page
                        buttonGrid1.timeBlock.Visibility = Visibility.Collapsed;
                    }
                    break;
                default:
                    break;
            }
            base.OnOrientationChanged(e);
        }
    }
}